package com.accloud.cloudservice;

import android.os.Handler;
import com.accloud.common.ACConfiguration;
import com.accloud.service.ACException;
import com.accloud.service.ACFileInfo;
import com.accloud.service.ACFileMgr;
import com.accloud.service.ACMsg;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RangeFileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.client.cache.HeaderConstants;
import cz.msebera.android.httpclient.cookie.ClientCookie;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.json.JSONObject;

public class ACFileManager extends ACBaseManager implements ACFileMgr {
    AsyncHttpClient client;
    Handler handler = new Handler();
    Map<String, Boolean> isCrcSuccess = new HashMap();
    Map<String, Boolean> uploadCancelledMap = new HashMap();
    UploadManager uploadManager;

    ACFileManager() {
        super(ACConfiguration.BLOBSTORE_SERVICE_NAME, 1, false);
    }

    @Override // com.accloud.service.ACFileMgr
    public void getDownloadUrl(ACFileInfo file, long expireTime, final PayloadCallback<String> callback) {
        ACMsg req = ACMsg.getACMsg("");
        req.setName("getDownloadUrl");
        req.put("bucket", file.getBucket());
        req.put("name", file.getFilename());
        req.put("expireTime", Long.valueOf(expireTime));
        sendReq(req, callback, new ACMsgListener() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass1 */

            @Override // com.accloud.cloudservice.ACMsgListener
            public void finish(ACMsg resp) {
                callback.success(resp.getString("downloadUrl"));
            }
        });
    }

    @Override // com.accloud.service.ACFileMgr
    public void downloadFile(final String url, final int crc, final ProgressCallback progressCallback, final PayloadCallback<byte[]> callback) {
        if (this.client == null) {
            this.client = new AsyncHttpClient();
        }
        this.isCrcSuccess.put(url, true);
        this.client.get(AC.context, url, new AsyncHttpResponseHandler() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass2 */

            @Override // com.loopj.android.http.AsyncHttpResponseHandler, com.loopj.android.http.ResponseHandlerInterface
            public Object getTag() {
                return url;
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                if (ACFileManager.this.isCrcSuccess.get(url).booleanValue()) {
                    callback.success(bytes);
                }
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onProgress(long bytesWritten, long totalSize) {
                if (progressCallback != null) {
                    progressCallback.progress(ACFileManager.getProgress((double) ((((float) bytesWritten) * 100.0f) / ((float) totalSize))).doubleValue());
                }
            }

            public void onCrcMessage(int getCrc) {
                if (crc > 0 && crc != getCrc) {
                    callback.error(new ACException(ACException.CHECK_CRC_FAILURE, "check crc failed"));
                    ACFileManager.this.isCrcSuccess.put(url, false);
                }
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                callback.error(new ACException(i, throwable));
            }
        });
    }

    public static Double getProgress(double percent) {
        DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
        format.applyPattern("0.00");
        return Double.valueOf(format.format(percent));
    }

    @Override // com.accloud.service.ACFileMgr
    public void downloadFile(File file, final String url, final int crc, final ProgressCallback progressCallback, final VoidCallback callback) {
        if (this.client == null) {
            this.client = new AsyncHttpClient();
        }
        this.isCrcSuccess.put(url, true);
        this.client.get(AC.context, url, new RangeFileAsyncHttpResponseHandler(file) {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass3 */

            @Override // com.loopj.android.http.AsyncHttpResponseHandler, com.loopj.android.http.ResponseHandlerInterface
            public Object getTag() {
                return url;
            }

            @Override // com.loopj.android.http.FileAsyncHttpResponseHandler
            public void onFailure(int i, Header[] headers, Throwable throwable, File file) {
                callback.error(new ACException(i, throwable));
            }

            @Override // com.loopj.android.http.FileAsyncHttpResponseHandler
            public void onSuccess(int i, Header[] headers, File file) {
                if (ACFileManager.this.isCrcSuccess.get(url).booleanValue()) {
                    callback.success();
                }
            }

            public void onCrcMessage(int getCrc) {
                if (crc > 0 && crc != getCrc) {
                    callback.error(new ACException(ACException.CHECK_CRC_FAILURE, "check crc failed"));
                    ACFileManager.this.isCrcSuccess.put(url, false);
                }
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onProgress(long bytesWritten, long totalSize) {
                if (progressCallback != null) {
                    progressCallback.progress(ACFileManager.getProgress((double) ((((float) bytesWritten) * 100.0f) / ((float) totalSize))).doubleValue());
                }
            }
        });
    }

    @Override // com.accloud.service.ACFileMgr
    public void cancelDownload(String url) {
        this.client.cancelRequestsByTAG(url, true);
    }

    @Override // com.accloud.service.ACFileMgr
    public void uploadFile(final ACFileInfo file, final ProgressCallback progressCallback, final VoidCallback callback) {
        if (!AC.accountMgr().isLogin()) {
            callback.error(new ACException(ACException.NO_LOGIN, "no login"));
        } else if (file.getData() == null && file.getFile() == null) {
            callback.error(new ACException(ACException.INVALID_PARAMETERS, "no input data"));
        } else if ((file.getData() == null || file.getData().length != 0) && (file.getFile() == null || file.getFile().length() != 0)) {
            String key = getUploadKey(file.getBucket(), file.getFilename());
            if (this.uploadCancelledMap.containsKey(key)) {
                this.uploadCancelledMap.put(key, false);
            }
            ACMsg req = ACMsg.getACMsg("");
            req.setName("uploadFileInfo");
            req.put(ClientCookie.VERSION_ATTR, 2);
            req.put("bucket", file.getBucket());
            req.put("name", file.getFilename());
            req.put("acl", file.getACL().toObject());
            if (file.isPublic()) {
                req.put("accessType", HeaderConstants.PUBLIC);
            } else {
                req.put("accessType", HeaderConstants.PRIVATE);
            }
            sendReq(req, callback, new ACMsgListener() {
                /* class com.accloud.cloudservice.ACFileManager.AnonymousClass4 */

                @Override // com.accloud.cloudservice.ACMsgListener
                public void finish(ACMsg resp) {
                    String storeType = resp.getString("storeType");
                    String token = resp.getString("uptoken");
                    String key = ACFileManager.this.getUploadKey(resp.getString("bucket"), resp.getString("name"));
                    if (storeType.equals("qiniu")) {
                        ACFileManager.this.uploadFileToQiniu(token, key, file, progressCallback, callback);
                    } else if (storeType.equals("aws")) {
                        ACFileManager.this.uploadFileToAws(token, file, progressCallback, callback);
                    }
                }
            });
        } else {
            callback.error(new ACException(ACException.INVALID_PARAMETERS, "file or data size is zero"));
        }
    }

    /* access modifiers changed from: package-private */
    public void uploadFileToQiniu(String token, final String key, ACFileInfo file, final ProgressCallback progressCallback, final VoidCallback callback) {
        this.uploadManager = this.uploadManager == null ? new UploadManager() : this.uploadManager;
        UploadOptions options = new UploadOptions(null, null, true, new UpProgressHandler() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass5 */

            @Override // com.qiniu.android.storage.UpProgressHandler
            public void progress(String key, final double percent) {
                if (progressCallback != null) {
                    ACFileManager.this.handler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACFileManager.AnonymousClass5.AnonymousClass1 */

                        @Override // java.lang.Runnable
                        public void run() {
                            progressCallback.progress(ACFileManager.getProgress(percent * 100.0d).doubleValue());
                        }
                    });
                }
            }
        }, new UpCancellationSignal() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass6 */

            @Override // com.qiniu.android.http.CancellationHandler
            public boolean isCancelled() {
                return ACFileManager.this.uploadCancelledMap.containsKey(key) && ACFileManager.this.uploadCancelledMap.get(key).booleanValue();
            }
        });
        UpCompletionHandler upCompletionHandler = new UpCompletionHandler() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass7 */

            @Override // com.qiniu.android.storage.UpCompletionHandler
            public void complete(String key, final ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    ACFileManager.this.handler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACFileManager.AnonymousClass7.AnonymousClass1 */

                        @Override // java.lang.Runnable
                        public void run() {
                            callback.success();
                        }
                    });
                } else {
                    ACFileManager.this.handler.post(new Runnable() {
                        /* class com.accloud.cloudservice.ACFileManager.AnonymousClass7.AnonymousClass2 */

                        @Override // java.lang.Runnable
                        public void run() {
                            callback.error(new ACException(ACException.INTERNAL_ERROR, info.error));
                        }
                    });
                }
            }
        };
        if (file.getData() != null) {
            this.uploadManager.put(file.getData(), key, token, upCompletionHandler, options);
        } else if (file.getFile() != null) {
            this.uploadManager.put(file.getFile(), key, token, upCompletionHandler, options);
        }
    }

    /* access modifiers changed from: package-private */
    public void uploadFileToAws(String url, final ACFileInfo fileInfo, final ProgressCallback progressCallback, final VoidCallback callback) {
        if (this.client == null) {
            this.client = new AsyncHttpClient();
        }
        RequestParams params = new RequestParams();
        if (fileInfo.getData() != null) {
            params.put("data", (InputStream) new ByteArrayInputStream(fileInfo.getData()));
        } else if (fileInfo.getFile() != null) {
            try {
                params.put("file", fileInfo.getFile());
            } catch (FileNotFoundException e) {
                callback.error(new ACException(ACException.INTERNAL_ERROR, e));
                return;
            }
        }
        if (fileInfo.isPublic()) {
            this.client.addHeader("x-amz-acl", "public-read");
        }
        this.client.put(AC.context, url, params, new AsyncHttpResponseHandler() {
            /* class com.accloud.cloudservice.ACFileManager.AnonymousClass8 */

            @Override // com.loopj.android.http.AsyncHttpResponseHandler, com.loopj.android.http.ResponseHandlerInterface
            public Object getTag() {
                return ACFileManager.this.getUploadKey(fileInfo.getBucket(), fileInfo.getFilename());
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onProgress(long bytesWritten, long totalSize) {
                if (progressCallback != null) {
                    progressCallback.progress(ACFileManager.getProgress((double) ((((float) bytesWritten) * 100.0f) / ((float) totalSize))).doubleValue());
                }
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                callback.success();
            }

            @Override // com.loopj.android.http.AsyncHttpResponseHandler
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                callback.error(new ACException(i, throwable));
            }
        });
    }

    @Override // com.accloud.service.ACFileMgr
    public void cancelUpload(ACFileInfo file) {
        if (this.uploadManager != null) {
            this.uploadCancelledMap.put(getUploadKey(file.getBucket(), file.getFilename()), true);
        } else {
            this.client.cancelRequestsByTAG(getUploadKey(file.getBucket(), file.getFilename()), true);
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private String getUploadKey(String bucket, String fileName) {
        return bucket + "/" + fileName;
    }
}
